package com.mogujie.tt.ui.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mogujie.tt.DB.sp.RegisterSp;
import com.mogujie.tt.R;
import com.mogujie.tt.config.MessageConstant;
import com.mogujie.tt.config.RegisterConstant;
import com.mogujie.tt.config.SysConstant;
import com.mogujie.tt.imservice.entity.ImageMessage;
import com.mogujie.tt.imservice.manager.IMLoginManager;
import com.mogujie.tt.imservice.service.LoadImageService;
import com.mogujie.tt.ui.base.QZBaseActivity;
import com.mogujie.tt.ui.base.TTBaseActivity;
import com.mogujie.tt.ui.widget.QuanzQzBimp;
import com.mogujie.tt.utils.FileUtil;
import com.mogujie.tt.utils.ImageUtil;
import com.mogujie.tt.utils.MoGuHttpClient;
import com.mogujie.tt.utils.SubmitUserDetailsTask;



public class MyUserInfoActivity extends QZBaseActivity {

    private RelativeLayout re_avatar;//个性化头像布局
    private RelativeLayout re_name;//昵称布局
    private RelativeLayout re_email;//邮箱布局
    private RelativeLayout re_sex;//性别布局
    private RelativeLayout re_region;
    private RelativeLayout re_sign;//个性签名

    private ImageView iv_avatar;//头像
    private TextView tv_name;//昵称
    private TextView tv_phone;//手机
    private TextView tv_sex;//性别
    private TextView tv_email;//邮箱
    private TextView tv_sign;//个性签名


    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private static final int UPDATE_EMAIL = 4;// 结果
    private static final int UPDATE_NICK = 5;// 结果
    private static final int UPDATE_SIGN = 6;// 结果

    String phone;
    String email;
    int sex;//性别
    String sign ="";//个性签名
    String nick;//昵称

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater.from(this).inflate(R.layout.tt_activity_myinfo, topContentView);
        showTopInformation("个人信息");
        initView();

    }

    private void initView() {

        nick = RegisterSp.instance().getSpDetailedInfo().getDetailedNickName();//得到昵称
        phone = RegisterSp.instance().getSpDetailedInfo().getDetailedMobilePhone();//得到手机号
        email = RegisterSp.instance().getSpDetailedInfo().getDetailedEmail();//得到邮箱
        sex =   RegisterSp.instance().getSpDetailedInfo().getDetailedSex();//性别
        sign =  RegisterSp.instance().getSpDetailedInfo().getDetailedSign();//个性签名
        String avatar = RegisterSp.instance().getSpDetailedInfo().getDetailedHeadPortrait();//得到头像


        re_avatar = (RelativeLayout) this.findViewById(R.id.re_avatar);//头像
        re_name = (RelativeLayout) this.findViewById(R.id.re_name);//昵称
        re_email = (RelativeLayout) this.findViewById(R.id.re_email);//邮箱
        re_sex = (RelativeLayout) this.findViewById(R.id.re_sex);//性别
        re_region = (RelativeLayout) this.findViewById(R.id.re_region);//设置地区
        re_sign = (RelativeLayout)this.findViewById(R.id.re_sign);//个性签名


        re_avatar.setOnClickListener(new MyListener());//设置头像监听
        re_name.setOnClickListener(new MyListener()); //设置昵称监听
        re_email.setOnClickListener(new MyListener());//设置邮箱监听
        re_sex.setOnClickListener(new MyListener());//设置性别监听
   //     re_region.setOnClickListener(new MyListener());
        re_sign.setOnClickListener(new MyListener());//设置个性签名监听

        // 头像
        iv_avatar = (ImageView) this.findViewById(R.id.iv_avatar);//头像显示
        tv_name = (TextView) this.findViewById(R.id.tv_name);//昵称显示
        tv_phone = (TextView) this.findViewById(R.id.tv_fxid);//手机显示
        tv_email =(TextView) this.findViewById(R.id.tv_email);//邮箱显示
        tv_sex = (TextView) this.findViewById(R.id.tv_sex);//性别显示
        tv_sign = (TextView) this.findViewById(R.id.tv_sign);//个性签名显示

        tv_name.setText(nick);//设置昵称
        tv_phone.setText(phone);//设置手机
        tv_email.setText(email);//设置邮箱

        //设置性别
        if (sex == 1) {
            tv_sex.setText("男");
        } else if (sex == 2) {
            tv_sex.setText("女");

        } else if(sex == 0){
            tv_sex.setText("保密");
        }

        //设置个性签名
        if (sign.equals("")) {
            tv_sign.setText("未填写");
        } else {
            tv_sign.setText(sign);
        }

        //设置头像显示
        showUserAvatar();
    }

    class MyListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.re_avatar:
                    showPhotoDialog();
                    break;
                case R.id.re_name:
                    startActivityForResult(new Intent(MyUserInfoActivity.this, UpdateNickActivity.class), UPDATE_NICK);
                    break;
                case R.id.re_email:
                    startActivityForResult(new Intent(MyUserInfoActivity.this, UpdateEmailActivity.class), UPDATE_EMAIL);
                    break;
                case R.id.re_sex:
                    showSexDialog();
                    break;
                case R.id.re_region:
                    break;
                case R.id.re_sign:
                    startActivityForResult(new Intent(MyUserInfoActivity.this, UpdateIndividualitySignActivity.class), UPDATE_SIGN);
                    break;

            }
        }

    }

    private void showPhotoDialog() {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.alertdialog);
        // 为确认按钮添加事件,执行退出应用操作
        TextView tv_paizhao = (TextView) window.findViewById(R.id.tv_content1);
        tv_paizhao.setText("拍照");
        tv_paizhao.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 指定调用相机拍照后照片的储存路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(RegisterConstant.PHOTO_PATH, RegisterConstant.IMAGE_FILE_NAME)));
                startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                dlg.cancel();
            }
        });
        TextView tv_xiangce = (TextView) window.findViewById(R.id.tv_content2);
        tv_xiangce.setText("相册");
        tv_xiangce.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                dlg.cancel();
            }
        });

    }

    private void showSexDialog() {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.alertdialog);
        LinearLayout ll_title = (LinearLayout) window.findViewById(R.id.ll_title);
        ll_title.setVisibility(View.VISIBLE);
        TextView tv_title = (TextView) window.findViewById(R.id.tv_title);
        tv_title.setText("性别");


        // 为确认按钮添加事件,执行退出应用操作
        TextView tv_paizhao = (TextView) window.findViewById(R.id.tv_content1);
        tv_paizhao.setText("男");
        tv_paizhao.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                tv_sex.setText("男");
                sex = 1;
                submitGender(sex);
                dlg.cancel();
            }
        });

        TextView tv_xiangce = (TextView) window.findViewById(R.id.tv_content2);
        tv_xiangce.setText("女");
        tv_xiangce.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                tv_sex.setText("女");
                sex = 2;
                submitGender(sex);
                dlg.cancel();
            }
        });

        window.findViewById(R.id.ll_content3).setVisibility(View.VISIBLE);
        TextView tv_secret = (TextView) window.findViewById(R.id.tv_content3);
        tv_secret.setText("保密");
        tv_secret.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                tv_sex.setText("保密");
                sex = 0;
                submitGender(sex);
                dlg.cancel();
            }
        });
    }

    private void submitGender(int sex){
        RegisterSp.instance().setdetailedSexIntConfig(sex);
        new SubmitUserDetailsTask(MyUserInfoActivity.this).execute();//提交用户详细信息
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case PHOTO_REQUEST_TAKEPHOTO:

                startPhotoZoom(
                        Uri.fromFile(new File(RegisterConstant.PHOTO_PATH, RegisterConstant.IMAGE_FILE_NAME)),
                        480);
                break;

            case PHOTO_REQUEST_GALLERY:
                if (data != null)
                    startPhotoZoom(data.getData(), 480);
                break;

            case PHOTO_REQUEST_CUT:
                // BitmapFactory.Options options = new BitmapFactory.Options();
                //
                // /**
                // * 最关键在此，把options.inJustDecodeBounds = true;
                // * 这里再decodeFile()，返回的bitmap为空
                // * ，但此时调用options.outHeight时，已经包含了图片的高了
                // */
                // options.inJustDecodeBounds = true;
                Bitmap bitmap = BitmapFactory.decodeFile(RegisterConstant.PHOTO_PATH
                        + RegisterConstant.IMAGE_FILE_TAILOR_NAME);
                iv_avatar.setImageBitmap(bitmap);
                updateAvatarInServer();
                break;


            }
            super.onActivityResult(requestCode, resultCode, data);

        } else if(resultCode == RESULT_CANCELED){
            switch (requestCode) {
                case UPDATE_NICK:
                    tv_name.setText(RegisterSp.instance().getSpDetailedInfo().getDetailedNickName());
                    break;
                case UPDATE_EMAIL:
                    tv_email.setText(RegisterSp.instance().getSpDetailedInfo().getDetailedEmail());
                    break;
                case UPDATE_SIGN:
                    tv_sign.setText(RegisterSp.instance().getSpDetailedInfo().getDetailedSign());
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 把头像上传到平台
     */
    private void updateAvatarInServer() {
        String path =  RegisterConstant.PHOTO_PATH + RegisterConstant.IMAGE_FILE_TAILOR_NAME;
        File file = new File(path);
        if(!file.exists()){
            return;
        }
        ImageMessage headPortrait = new ImageMessage();
        headPortrait.setPath(path);
        headPortrait.setLoadStatus(MessageConstant.IMAGE_UNLOAD_AVATOR);
        Intent loadImageIntent = new Intent(MyUserInfoActivity.this, LoadImageService.class);
        loadImageIntent.putExtra(SysConstant.UPLOAD_IMAGE_INTENT_PARAMS, headPortrait);
        MyUserInfoActivity.this.startService(loadImageIntent);

        new UploadPicturesAsynchronous().execute();
    }



    private void startPhotoZoom(Uri uri1, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri1, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", false);

        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(RegisterConstant.PHOTO_PATH, RegisterConstant.IMAGE_FILE_TAILOR_NAME)));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }


    private String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSS");
        return dateFormat.format(date);
    }


    /**
     * 显示个性化头像
     */
    private void showUserAvatar() {

        String path = RegisterConstant.PHOTO_PATH + RegisterConstant.IMAGE_FILE_TAILOR_NAME;
        File file = new File(path);
        if(file.exists()) {
            iv_avatar.setImageBitmap(ImageUtil.getBigBitmapForDisplay(path, MyUserInfoActivity.this));
        }else{
            iv_avatar.setImageResource(R.drawable.tt_default_user_portrait_corner);
        }

    }


    /**
     * 显示顶部信息
     */
    private void showTopInformation(String test){
        if(test == null){
            return;
        }
        setTopBarDisplay();

        setCenterText(test);
    }


    public void onClickExit(View view){
        finish();
    }

    private class UploadPicturesAsynchronous extends AsyncTask<Void,Void,Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                final Map<String, String> param = new HashMap<String, String>();
                param.put("uid", String.valueOf(IMLoginManager.instance().getLoginId()));
                final Map<String, File> files = new HashMap<String, File>();
                String path = "/storage/emulated/0/DCIM/faceImage_tailor.jpg";
                Bitmap bm = QuanzQzBimp.revitionImageSize(path);
                String newStr = path.substring(
                        path.lastIndexOf("/") + 1,
                        path.lastIndexOf("."));
                File file1 = FileUtil.saveBitmap(bm, newStr);
                files.put("uploadfile1", file1);
                MoGuHttpClient moGuHttpClient = new MoGuHttpClient();
                //  String request = moGuHttpClient.postImg("http://192.168.10.33:8080/uploadImage/UploadAvatarServlet.do", param, files);
                String request = moGuHttpClient.postImg("http://qz.atmart.cn:4025/uploadImage/UploadAvatarServlet.do",param, files);
                //	System.out.print(request);
                //   Log.v("111111111111", "request = " + request);
            }catch (Exception e){

            }
            return null;
        }
    }
}
